﻿

//debugger;
// actionFlag: 1 -> 新增；2 -> 修改；3 -> 查看
var actionFlag = getPar1("actionFlag");
var const_UserId = parent.parent._currentUserID;
var const_UserName = parent.parent._currentUserName;
var transCode = getPar1("transcode");
var curTrans;
var invAdjustFlag;     // 在库调整标识

$(document).ready(function () {
    getTCode();

    if (curTrans == "" || curTrans == null) {
        alert("相应的事务代码: [" + transCode + "] 还未定义, 当前操作不能继续!");
        parent.parent.CloseCurPage();
        return;
    }

    invAdjustFlag = (curTrans.rows[0].ToBuCondition == "" ? 1 : 0);       // 是否在库调整

    if (actionFlag == 1) {
        obj = $("#SystemGenNo");
        sequenceName = curTrans.rows[0].SequenceName;
        genNewSequenceNo(obj, sequenceName);

        fromBuCondition = curTrans.rows[0].FromBuCondition;
        toBuCondition = curTrans.rows[0].ToBuCondition;
        //debugger;
        $("#FromBu").attr("condition", fromBuCondition);
        $("#ReceiveBu").attr("condition", toBuCondition);

        // 在库调整ToBuCondition = ""时将ReceiveBu对应控件Disabled
        if (invAdjustFlag == 1) {
            $("#ReceiveBu").attr("disabled", "disabled");
        }

        setFromWarehouse(curTrans.rows[0].FromLoc);
        //alert($("#FromWarehouse").get(0).options[$("#FromWarehouse").get(0).options.selectedIndex].value);
        setToWarehouse(curTrans.rows[0].ToLoc);
        //debugger;
        setTransCode(curTrans.rows[0].TransCode);

        $("#ReceiveNo").focus();
        $("#AddUserName").val(const_UserName);
    }
    else {
        setFromWarehouse(instance[0].FromWarehouse);
        setToWarehouse(instance[0].ReceiveWarehouse);
        setTransCode(curTrans.rows[0].TransCode);

        // 加载明细表中下拉列表的数据
        //setDWListData();

    }

    $("#FromWarehouse").attr("disabled", "disabled");
    $("#ReceiveWarehouse").attr("disabled", "disabled");
    $("#TransCode").attr("disabled", "disabled");

    $("#ReceiveNo").bind("change", function () { var receiveNo = $(this).val().toUpperCase(); fnCheckReceiveNo(receiveNo); });
});

// 读取当前T_Code相关资料
var getTCode = function () {
    curTrans = fnGetData("BH_T_Code", "TransCode='" + transCode + "'");
}

// 设置发货仓库
var setFromWarehouse = function (warehouse) {
    //document.getElementById("BOMNo").options.length = 0;
    $("#FromWarehouse").get(0).options.length = 0;
    
    warehouseList = fnGetData("V_DatPhraseDetail", "ClassValue='Warehouse'");  // and PhraseValue='" + warehouse + "'");
    if (warehouseList == null || warehouseList == "") {
        //alert("不存在任何仓库定义!");
        $("#FromWarehouse").append("<option value='" + "" + "'>" + "" + "</option>");
        return;
    }

    $("#FromWarehouse").append("<option value='" + "" + "'>" + "" + "</option>");

    if (warehouseList.total > 0) {
        for (var i = 0; i < warehouseList.total; i++) {
            if (warehouseList.rows[i].PhraseText != undefined) {
                selected = warehouseList.rows[i].PhraseValue == warehouse ? "selected='selected'" : ""
                $("#FromWarehouse").append("<option value='" + warehouseList.rows[i].PhraseValue + "'" + selected + ">" + warehouseList.rows[i].PhraseText + "</option>");
            }
        }
    }
}

// 设置收货仓库
var setToWarehouse = function (warehouse) {
    //document.getElementById("BOMNo").options.length = 0;
    $("#ReceiveWarehouse").get(0).options.length = 0;
    
    warehouseList = fnGetData("V_DatPhraseDetail", "ClassValue='Warehouse'");  // and PhraseValue='" + warehouse + "'");
    if (warehouseList == null || warehouseList == "") {
        //alert("不存在任何仓库定义!");
        $("#ReceiveWarehouse").append("<option value='" + "" + "'>" + "" + "</option>");
        return;
    }

    $("#ReceiveWarehouse").append("<option value='" + "" + "'>" + "" + "</option>");

    if (warehouseList.total > 0) {
        for (var i = 0; i < warehouseList.total; i++) {
            if (warehouseList.rows[i].PhraseText != undefined) {
                selected = warehouseList.rows[i].PhraseValue == warehouse ? "selected='selected'" : ""
                $("#ReceiveWarehouse").append("<option value='" + warehouseList.rows[i].PhraseValue + "'" + selected + ">" + warehouseList.rows[i].PhraseText + "</option>");
            }
        }
    }
}

// 设置入库原因
var setTransCode = function (transCode) {
    $("#TransCode").get(0).options.length = 0;
    
    transCodeList = fnGetData("BH_T_Code", "");
    if (transCodeList == null || transCodeList == "") {
        $("#TransCode").append("<option value='" + "" + "'>" + "" + "</option>");
        return;
    }

    if (transCodeList.total > 0) {
        for (var i = 0; i < transCodeList.total; i++) {
            if (transCodeList.rows[i].TransCode != undefined) {
                selected = transCodeList.rows[i].TransCode == transCode ? "selected='selected'" : ""
                $("#TransCode").append("<option value='" + transCodeList.rows[i].TransCode + "'" + selected + ">" + transCodeList.rows[i].Reason + "</option>");
            }
        }
    }
}


// 检测部品入库单编号是否重复
var fnCheckReceiveNo = function (val) {
    if (val != "") {
        var receiveNo = fnGetData("V_BH_InsYarns", "ID<>'" + instance[0].ID.toString() + "' and ReceiveNo='" + val + "'");
        if (receiveNo != null && receiveNo != "") {
            alert("部品入库单编号: [ " + val + " ] 已存在, 请重新输入!");
            setTimeout(function () {
                $("#ReceiveNo").focus();
                $("#ReceiveNo").val("");
            }, 10);
        }
    }
}

var getCompanyData = function (company) {
    return fnGetData("BH_Company", "CompanyNo='" + company + "' or CompanyName='" + company + "' or ShortName='" + company + "'");
}


// 设置供应商名称
var setCompanyName = function (i) {
    companyNo = "";

    if (i == 1) {
        companyNo = $("#FromBu").attr("SValue");
    }
    else if (i == 2) {
        companyNo = $("#ReceiveBu").attr("SValue");
    }
    
    Company = getCompanyData(companyNo);

    if (Company == null || Company == "") {
        alert("单位：" + companyNo + " 还未定义!");

        if (i == 1) {
            $("#FromBuName").val("");
            $("#FromBu").focus();
        }
        else if (i == 2) {
            $("#ReceiveBuName").val("");
            $("#ReceiveBu").focus();
        }
        return;
    }

    if (i == 1) {
        $("#FromBuName").val(Company.rows[0].CompanyName);
    }
    else if (i == 2) {
        $("#ReceiveBuName").val(Company.rows[0].CompanyName);
    }
}


var fnCustomeRowAddEvent = function (trs, i) {
    _DataTable.Rows[i].ID = "00000000-0000-0000-0000-000000000000";
    setLineNo();

    var weightObj = trs.find("input[name='NetWeight']");
    weightObj.numberbox({
        min: -9999999999,
        precision: 2
    });
    //weightObj.bind("change", function () { var t = $(this).val(); var o = trs; calcAmount(o); });
    weightObj.bind("blur", function () { var t = $(this).val(); var o = trs; calcAmount(o); });
    weightObj.val("0.00");

    var shortWeightObj = trs.find("input[name='ShortWeight']");
    shortWeightObj.numberbox({
        min: -9999999999,
        precision: 2
    });
    shortWeightObj.bind("blur", function () { var t = $(this).val(); var o = trs; calcAmount(o); });
    shortWeightObj.val("0.00");

    var qtyObj = trs.find("input[name='Qty']");
    qtyObj.numberbox({
        min: 1,
        precision: 0
    });
    //qtyObj.bind("change", function () { var t = $(this).val(); var o = trs; calcAmount(o); });
    qtyObj.bind("blur", function () { var t = $(this).val(); var o = trs; calcAmount(o); });
    qtyObj.val("1");

    var priceObj = trs.find("input[name='StandPrice']");
    priceObj.numberbox({
        min: 0,
        precision: 2
    });
    //priceObj.bind("change", function () { var t = $(this).val(); var o = trs; calcAmount(o); });
    priceObj.bind("blur", function () { var t = $(this).val(); var o = trs; calcAmount(o); });
    priceObj.val("0.00");

    trs.find("input[name='Amount']").val("0.00");

    var o = trs.find("input[name='ItemNo']");
    //o.bind("change", function () { var t = $(this).val(); var o = trs; setItemDetail(t, o); });
    o.bind("blur", function () { var t = $(this).val(); var o = trs; setItemDetail(t, o); });
    o.focus();
    o.click();

    if (curTrans.rows[0].NeedOrderFlag == "False") {
        trs.find("select[name='OrderNo']").attr("disabled", "disabled");
    }
}

var fnCustomeRowDelEvent = function () {
    setLineNo();
}

var customSetEvent = function () {
    if (actionFlag != "1") {
        //setDWListData();
    }

    if (actionFlag == "2") {
        var now = new Date();
        $("#ItemNo").attr("disabled", "disabled");
        parent.setAddNewButtonHiden();
        //debugger;
        var trs = $("#Details tbody tr");
        if (trs.length >= 1) {
            trs.each(function (em) {
                $(trs[em]).find("input[name='ItemNo']").attr("disabled", "disabled");
                $(trs[em]).find("input[name='NetWeight']").attr("disabled", "disabled");
                $(trs[em]).find("input[name='Qty']").attr("disabled", "disabled");
                $(trs[em]).find("input[name='StandPrice']").attr("disabled", "disabled");
                $(trs[em]).find("input[name='TotalWeight']").attr("disabled", "disabled");
                $(trs[em]).find("input[name='ShortWeight']").attr("disabled", "disabled");
                $(trs[em]).find("input[name='RealWeight']").attr("disabled", "disabled");
            });
        }
    }

    if (curTrans.rows[0].GetOrderFlag == "True") {
        $("#data_head td:eq(5)").html("已收货量");
    }

    if (curTrans.rows[0].NeedOrderFlag == "False") {
        $("#data_head td:eq(5)").html("在库重量");
    }
}

var setLineNo = function () {
    var trs = $("#Details tbody tr");
    if (trs.length >= 1) {
        var seq = 1;
        trs.each(function (em) {
            $(trs[em]).find("input[name='LineNo']").val(seq.toString());
            seq = seq + 1;
        });
    }
}

var getItemData = function (item) {
    return fnGetData("BH_ItemMaster", "ItemNo='" + item + "' or ItemModel='" + item + "' or ItemName='" + item + "'");
}

var setItemDetail = function (itemNo, o) {
    if (itemNo != "" && itemNo != null) {

        if (checkEmptyFromBu() == false) {
            o.find("input[name='ItemNo']").val("");
            o.find("input[name='ItemModel']").val("");
            o.find("input[name='ItemName']").val("");
            return;
        }

        ItemDetail = getItemData(itemNo);

        if (ItemDetail == null || ItemDetail == "") {
            alert("物料：" + itemNo + " 还未定义!");
            o.find("input[name='ItemNo']").val("");
            o.find("input[name='ItemModel']").val("");
            o.find("input[name='ItemName']").val("");
            o.find("select[name='OrderNo']").get(0).options.length = 0;
            o.find("input[name='NetWeight']").val("0.00");
            o.find("input[name='Qty']").val("1");
            o.find("input[name='TotalWeight']").val("0.00");
            o.find("input[name='ShortWeight']").val("0.00");
            o.find("input[name='RealWeight']").val("0.00");
            o.find("input[name='StandPrice']").val("0.00");
            o.find("input[name='Amount']").val("0.00");
            setTimeout(function () {
                o.find("input[name='ItemNo']").focus();
            }, 10);
            return;
        }

        // 加载订单资料
        //debugger;
        if (curTrans.rows[0].NeedOrderFlag == "True") {
            var companyNo = (curTrans.rows[0].GetOrderFlag == "True") ? $("#ReceiveBu").attr("SValue") : $("#FromBu").attr("SValue");
            if (getPurchaseOrder(o, companyNo) == false) {
                return;
            }
        }
        else {
            getInvBalance(o, $("#FromBu").attr("SValue"), $("#FromWarehouse").get(0).options[$("#FromWarehouse").get(0).selectedIndex].text);
        }

        o.find("input[name='ItemNo']").val(ItemDetail.rows[0].ItemNo);
        o.find("input[name='ItemModel']").val(ItemDetail.rows[0].ItemModel);
        o.find("input[name='ItemName']").val(ItemDetail.rows[0].ItemName);
    }
}

// 明细表当前行单价或重量改变时计算金额
var calcAmount = function (o) {
    netWeight = parseFloat(o.find("input[name='NetWeight']").val().toString());
    qty = parseFloat(o.find("input[name='Qty']").val().toString());
    shortWeight = parseFloat(o.find("input[name='ShortWeight']").val().toString());
    standPrice = parseFloat(o.find("input[name='StandPrice']").val().toString());
    poBal = parseFloat(o.find("input[name='POBal']").val().toString());

    if (netWeight * qty > poBal) {
        if (curTrans.rows[0].GetOrderFlag == "True") {
            alert("退货量大于当前订单的已收货量");
        }
        else {
            alert("收货量大于当前订单的未收货量");
        }

        o.find("input[name='Qty']").val("1");
        setTimeout(function () {
            o.find("input[name='NetWeight']").focus();
        }, 10);
        return;
    }

    o.find("input[name='TotalWeight']").val((netWeight * qty).toFixed(2));
    o.find("input[name='RealWeight']").val((netWeight * qty - shortWeight).toFixed(2));
    o.find("input[name='Amount']").val((netWeight * qty * standPrice).toFixed(2));
}

// 检测发货单位不能为空才能填写收货明细
var checkEmptyFromBu = function () {
    fromBu = $("#FromBu").attr("SValue");

    if (fromBu == null || fromBu == "") {
        alert("发货单位不能为空");
        $("#FromBu").focus();
        return false;
    }

    return true;
}

// 加载指定的部品所在转出单位相应仓库的在库数
var getInvBalance = function (trs, vendorNo, warehouse) {
    itemNo = trs.find("input[name='ItemNo']").val();
    invBalance = fnGetData("V_BH_InvBalance", "CompanyNo='" + vendorNo + "' and ItemNo='" + itemNo + "' and WarehouseName='" + warehouse + "'");
    //debugger;
    if (invBalance != null && invBalance != "") {
        trs.find("select[name='OrderNo']").get(0).options.length = 0;
        trs.find("input[name='POBal']").val(parseFloat(invBalance.rows[0].Weight).toFixed(2));
    }
    else {
        trs.find("input[name='POBal']").val("0.00");
    }

}

// 加载指定的部品&供应商相关的订单信息
var getPurchaseOrder = function (trs, vendorNo) {
    itemNo = trs.find("input[name='ItemNo']").val();
    if (curTrans.rows[0].GetOrderFlag == "True") {
        poBalance = fnGetData("V_BH_PurchaseOrderDetail", "VendorNo='" + vendorNo + "' and ItemNo='" + itemNo + "' and RWeight <> 0");
    }
    else {
        poBalance = fnGetData("V_BH_PurchaseOrderDetail", "VendorNo='" + vendorNo + "' and ItemNo='" + itemNo + "' and Weight > RWeight");
    }

    if (poBalance == null || poBalance == "") {
        alert("供应商: " + vendorNo + " 不存在部品: " + itemNo + " 的相关订单资料，不能进行收货动作!");
        trs.find("input[name='ItemNo']").val("");
        trs.find("input[name='ItemModel']").val("");
        trs.find("input[name='ItemName']").val("");
        trs.find("select[name='OrderNo']").get(0).options.length = 0;
        trs.find("input[name='NetWeight']").val("0.00");
        trs.find("input[name='Qty']").val("1");
        trs.find("input[name='TotalWeight']").val("0.00");
        trs.find("input[name='ShortWeight']").val("0.00");
        trs.find("input[name='RealWeight']").val("0.00");
        trs.find("input[name='StandPrice']").val("0.00");
        trs.find("input[name='Amount']").val("0.00");
        setTimeout(function () {
            trs.find("input[name='ItemNo']").focus();
        }, 10);
        return false;
    }

    // 生成订单列表
    orderList = trs.find("select[name='OrderNo']");
    orderList.get(0).options.length = 0;
    if (poBalance.total > 0) {
        for (var i = 0; i < poBalance.total; i++) {
            if (poBalance.rows[i].OrderNo != undefined) {
                orderList.append("<option value='" + poBalance.rows[i].OrderNo + "'>" + poBalance.rows[i].OrderNo + "</option>");
            }
        }
    }
    orderList.bind("change", function () { var t = $(this).val(); var o = trs; getPOBal(o, t); });
    orderList.bind("blur", function () { var t = $(this).val(); var o = trs; getPOBal(o, t); });

    orderList.get(0).options.selectedIndex = 0;
    orderList.change();

    return true;
}

// 指定的订单读取其未收货数量
var getPOBal = function (trs, orderNo) {
    itemNo = trs.find("input[name='ItemNo']").val();

    poBal = fnGetData("V_BH_PurchaseOrderDetail", "OrderNo='" + orderNo + "' and ItemNo='" + itemNo + "'");
    if (poBal == null || poBal == "") {
        trs.find("input[name='POBal']").val("0.00");
        trs.find("input[name='StandPrice']").val("0.00");
        return;
    }
    if (curTrans.rows[0].GetOrderFlag == "True") {
        trs.find("input[name='POBal']").val(parseFloat(poBal.rows[0].RWeight).toFixed(2).toString());
    }
    else {
        trs.find("input[name='POBal']").val(parseFloat(poBal.rows[0].Weight - poBal.rows[0].RWeight).toFixed(2).toString());
    }
    trs.find("input[name='StandPrice']").val(parseFloat(poBal.rows[0].StandPrice).toFixed(2));
}

// 提交检测
var fnCustomCheck = function () {
    if (instance[0].ReceiveNo == "" || instance[0].ReceiveNo == null) {
        $("#ReceiveNo").focus();
        return "收货单编号不能为空!";
    }
    if (instance[0].ReceiveDate == "" || instance[0].ReceiveDate == null) {
        $("#ReceiveDate").focus();
        return "收货日期不能为空!";
    }
    if (instance[0].FromBu == "" || instance[0].FromBu == null) {
        $("#FromBu").focus();
        return "发货单位不能为空!";
    }
    if (invAdjustFlag == 0) {
        if (instance[0].ReceiveBu == "" || instance[0].ReceiveBu == null) {
            $("#ReceiveBu").focus();
            return "收货单位不能为空!";
        }
    }
    return "";
}

// 查看时填充下拉列表框数据
var setDWListData = function () {
    var trs = $("#Details tbody tr");
    trs.each(function (em) {
        //debugger;
        curValue = _DataTable.Rows[em].OrderNo;
        tt = $(trs[em]);
        var orderNo = tt.find("select[name='OrderNo']");
        debugger;
        orderNo.get(0).options.length = 0;
        orderNo.append("<option value='" + curValue + "' selected='selected'>" + curValue + "</option>");
        orderNo.attr("value", curValue);
        //orderNo.attr("disabled", "disabled");
    });
}


// 检测明细表中的记录是否录入
var fnCheckDetail = function () {
    var trs = $("#Details tbody tr");
    var errorFlag = 0;

    if (trs.length < 1) {
        alert("收货部品列表中不存在任何部品!");
        return false;
    }

    trs.each(function (em) {
        var itemNo = $(trs[em]).find("input[name='ItemNo']");
        var netWeight = $(trs[em]).find("input[name='NetWeight']");
        var orderNo = $(trs[em]).find("select[name='OrderNo']");
        var standPrice = $(trs[em]).find("input[name='StandPrice']");
        //debugger;
        if (itemNo.val() == "") {
            alert("部品列表中的部品编号不能为空!");
            itemNo.focus();
            errorFlag = 1;
            return false;
        }

        if (parseFloat(netWeight.val().toString()) == 0) {
            alert("部品列表中的单重不能为0!");
            netWeight.focus();
            errorFlag = 1;
            return false;
        }

        if (curTrans.rows[0].NeedOrderFlag == "True") {
            if (orderNo.val().toString() == "" || orderNo.val().toString() == null) {
                alert("列表中的订单号码不能为空!");
                orderNo.focus();
                errorFlag = 1;
                return false;
            }
        }

        /*
        if (parseFloat(standPrice.val().toString()) == 0) {
        alert("部品列表中的部品单价不能为0!");
        standPrice.focus();
        errorFlag = 1;
        return false;
        }
        */
    });

    if (errorFlag == 1) {
        return false;
    }

    return true;
}


var fnSetValue = function () {
    instance[0].ReceiveNo = instance[0].ReceiveNo.toUpperCase();
    instance[0].AddUser = const_UserId;
    if (actionFlag == "1") {
        curDate = new Date();
        instance[0].AddTime = fnGetMyDate(curDate);
    }
}

// 保存数据
var fnCustomSave = function () {
    //debugger;
    if (fnCheckDetail() == false) {
        return;
    }

    fnSetValue();
    dataAction = (actionFlag == "1") ? "A" : "C";

    if (typeof (_DataTable) != "undefined") {
        if (fnCheckEmpty() == false) {
            alert("明细数据没有录入");
        }
        _DataTable.GetData();

        detailJson = $.toJSON(_DataTable.Rows).replace(/'/g, "[B]").replace(/\+/g, "[J]")
    }

    json = $.toJSON(instance[0]).replace(/'/g, "[B]").replace(/\+/g, "[J]");
    //debugger;
    $.ajax({
        async: false, //异步请求
        cache: false, //不从浏览器缓存中加载
        type: "GET",
        /*dataType: "json",*/
        url: "/DCBH/DCBHCommonOperator.aspx",
        data: { Action: "procedure", entity: "V_BH_InsYarns", json: json, detailJson: detailJson, dataAction: dataAction },
        success: function (data) {
            //debugger;
            if (data != "") {
                if (data == "1") {
                    alert("数据保存成功!");

                    if (parent.SaveAndAddNewFlag == true) {
                        location.href = location.href
                    }

                    if (parent.SaveSuccessClose == true) {
                        parent.parent.CloseCurPage();
                    }
                }
                else {
                    alert(data);
                }
            }
        },
        error: function (e) {
            alert("保存失败, 请联系开发人员，核查系统！");
            return;
        }
    });

} 